package com.polaris.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.polaris.common.utils.RespBean;
import com.polaris.server.dto.AdminLoginParam;
import com.polaris.server.dto.UserCreateParam;
import com.polaris.server.dto.UserUpdateParam;
import com.polaris.server.mapper.SysRoleMapper;
import com.polaris.server.mapper.SysUserMapper;
import com.polaris.server.mapper.SysUserRoleMapper;
import com.polaris.server.pojo.*;

import com.polaris.server.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台管理Service的控制器
 * @author polaris
 * @version 1.0
 */
@Api(tags = "管理模块")
@RestController
@RequestMapping("/api")
public class AdminController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    private final IAdminService adminService;
    private final ISysUserService userService;
    private final ISysUserRoleService adminRoleRelationService;
    private final ISysDeptService deptService;
    private final ISysUserJobService userJobService;
    private final ISysJobService jobService;
    private final IMonitorService monitorService;
    private final SysUserRoleMapper adminRoleRelationMapper;
    private final SysRoleMapper roleMapper;

    public AdminController(IAdminService adminService, ISysUserService userService, ISysUserRoleService adminRoleRelationService, ISysDeptService deptService, ISysUserJobService userJobService, ISysJobService jobService, IMonitorService monitorService, SysUserRoleMapper adminRoleRelationMapper, SysUserMapper userMapper, SysRoleMapper roleMapper) {
        this.adminService = adminService;
        this.userService = userService;
        this.adminRoleRelationService = adminRoleRelationService;
        this.deptService = deptService;
        this.userJobService = userJobService;
        this.jobService = jobService;
        this.monitorService = monitorService;
        this.adminRoleRelationMapper = adminRoleRelationMapper;
        this.roleMapper = roleMapper;
    }

    @ApiOperation(value = "登陆")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam, HttpServletRequest request){
        return adminService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(),request);
    }
    @ApiOperation(value = "测试出错")
    @RequestMapping("/error")
    public String error(){
        return "error";
    }

    @ApiOperation(value = "获取当前登陆用户信息")
    @GetMapping("/admin/info")
    @ResponseBody
    public RespBean getAdminUserInfo(Principal principal){
        if(principal == null){
            return RespBean.error("获取用户信息失败");
        }
        String username = principal.getName();
        SysUser user = adminService.getAdminByUserName(username);
        SysRole role = adminRoleRelationService.getAdminRoleRelationByUserId(user.getUserId());
        SysDept dept = deptService.getById(user.getDeptId());
        SysUserJob userJob = userJobService.getOne(new QueryWrapper<SysUserJob>().eq("user_id", user.getUserId()));
        SysJob job = jobService.getById(userJob.getJobId());

        Map<String,Object> data = new HashMap<>();
        data.put("username", user.getUsername());
        data.put("job", job.getName());
        data.put("avatar",user.getAvatar());
        data.put("email", user.getEmail());
        data.put("phone", user.getPhone());
        data.put("role", role);

        dept.setCreateBy(null);
        dept.setUpdateBy(null);
        dept.setCreateTime(null);
        dept.setUpdateTime(null);
        dept.setSubCount(null);

        data.put("dept", dept);
        return RespBean.success("获取用户信息成功",data);
    }
    @ApiOperation(value = "刷新token")
    @GetMapping(value = "/refreshToken")
    public RespBean refreshToken(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        String refreshToken = adminService.refreshToken(token);
        if (refreshToken == null){
            return RespBean.error("token已经过期！");
        }
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return RespBean.success("刷新token成功",tokenMap);
    }
    @ApiOperation(value = "退出登陆")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("注销成功");
    }

    @ApiOperation(value = "管理员创建新用户")
    @PostMapping("/admin/user/add")
    public RespBean create(Principal principal, @RequestBody UserCreateParam createParam){
        SysUser user = adminService.getAdminByUserName(principal.getName());
        if(user.getIsAdmin() == 1){
            return adminService.create(createParam);
        } else {
            return RespBean.error("仅管理员用户能够进行本操作");
        }
    }

    @ApiOperation(value = "管理员删除用户")
    @PostMapping("/admin/user/delete")
    public RespBean delete(Principal principal, @RequestParam(value = "id") Integer id){
        SysUser users = adminService.getAdminByUserName(principal.getName());
        if(users.getIsAdmin() == 1){
            return adminService.delete(id);
        } else {
            return RespBean.error("仅管理员用户能够进行本操作");
        }
    }

    @ApiOperation(value = "管理员修改其他用户的账户是否启用")
    @PostMapping("/admin/user/enable")
    public RespBean enable(Principal principal,
                           @RequestParam(value = "id", required = true) Integer id,
                           @RequestParam(value = "enable",defaultValue = "0") Integer enable){
        SysUser users = adminService.getAdminByUserName(principal.getName());
        if(users.getIsAdmin()==1){
            return adminService.updateEnable(id, enable);
        }
        else{
            return RespBean.error("仅管理员用户能够进行本操作");
        }
    }
    @PostMapping("/admin/update/dept")
    @ApiOperation(value = "修改用户的所属部门")
    public RespBean updateDept(Principal principal, @RequestBody UserUpdateParam updateParam){
        SysUser admin = adminService.getAdminByUserName(principal.getName());
        Long roleId = adminRoleRelationMapper.selectOne(new QueryWrapper<SysUserRole>().eq("admin_id", admin.getUserId())).getRoleId();
        SysRole role = roleMapper.selectOne(new QueryWrapper<SysRole>().eq("roleId",roleId));

        if(admin.getIsAdmin()==1 || role.getLevel()==1){
            SysUser user = userService.updateDept(updateParam.getUser_id(), updateParam.getDept());
            if(user==null){
                return RespBean.error("更新用户所属部门失败");
            }
            return RespBean.success("更新用户所属部门成功");
        }
        return RespBean.error("无权进行该项查询操作");
    }

    @PostMapping("/admin/update/job")
    @ApiOperation(value = "修改用户的职位")
    public RespBean updateJob(Principal principal, @RequestBody UserUpdateParam updateParam){
        SysUser admin = adminService.getAdminByUserName(principal.getName());
        Long roleId = adminRoleRelationMapper.selectOne(new QueryWrapper<SysUserRole>().eq("admin_id", admin.getUserId())).getRoleId();
        SysRole role = roleMapper.selectOne(new QueryWrapper<SysRole>().eq("roleId",roleId));

        if(admin.getIsAdmin()==1||role.getLevel()==1){
            SysUser user = userService.updateJob(updateParam.getUser_id(), updateParam.getJob_id());
            if(user==null){
                return RespBean.error("更新用户职位失败");
            }
            return RespBean.success("更新用户职位成功");
        }
        return RespBean.error("无权进行该项查询操作");
    }
    @GetMapping("/monitor")
    @ApiOperation("查询服务监控")
    public RespBean query(){
        return RespBean.success("查询服务监控成功",monitorService.getServers());
    }
}
